<template>
  <div class="view-fill">
    <div class="app-container-flex">
      <NewFullScreen
        v-model="showDialog"
        title="采购单明细"
        :needOperateAffair="true"
        :operateAffairData="affairTableInfo"
        @returnBack="returnBack"
      >
        <template v-slot:full-button>
          <el-button
            v-if="
              $permission('purchOrder:update') && infoList.data.status === 1
            "
            @click="update"
            >修改</el-button
          >
          <el-button v-if="canPrint" @click="print">打印</el-button>
          <el-button v-if="canExcel" @click="exportExcel">导出excel</el-button>
          <el-button v-if="canRevoke" @click="handelMethodRequest('revoke')"
            >撤回
          </el-button>
          <el-button v-if="canRatify" @click="handelMethodRequest('ratify')"
            >批准
          </el-button>
          <el-button v-if="canBreak" @click="handelMethodRequest('stop')"
            >中止
          </el-button>
          <el-button v-if="canSubmit" @click="handelMethodRequest('submit')"
            >提交
          </el-button>
          <el-button v-if="canReject" @click="handelMethodRequest('reject')"
            >驳回</el-button
          >
          <el-button v-if="canSplit" @click="handelMethodRequest('split')"
            >拆单</el-button
          >
          <el-button v-if="canDoPurch" @click="handelMethodRequest('doPurch')"
            >采购</el-button
          >
          <el-button
            v-if="$permission('purchOrder:saveCopeTemplat')"
            @click="saveCopeTemplate()"
            >另存为模板</el-button
          >
          <el-button
            v-if="$permission('purchOrder:copy')"
            @click="copyPurchOrder()"
            >拷贝</el-button
          >
        </template>
        <div class="model-panel">
          <div class="model-panel-title">
            <p>{{ $t('basic_information') }}</p>
          </div>
          <div class="model-panel-body">
            <basic-information :info="infoList">
              <template v-slot:basic-applicationNo>
                <div class="flex_wrap_start_start">
                  <div
                    v-if="$permission('purchOrder:detail')"
                    class="detail_item_text slip-edit"
                    @click="showPurchAppDetail(infoList.data)"
                  >
                    {{ infoList.data.applicationNo }}
                  </div>
                  <div v-else class="detail_item_text slip-edit">
                    {{ infoList.data.applicationNo }}
                  </div>
                </div>
              </template>
              <template v-slot:basic-mergedOrders>
                <span
                  v-if="
                    infoList.data.mergedOrders &&
                    infoList.data.mergedOrders.length <= 3
                  "
                >
                  <span
                    v-for="(item, itemIndex) in infoList.data.mergedOrders"
                    :key="itemIndex"
                  >
                    <a class="slip-edit" @click="getNew(item.id)">{{
                      item.orderNo
                    }}</a>
                    <span
                      v-if="itemIndex < infoList.data.mergedOrders.length - 1"
                      >,</span
                    >
                  </span>
                </span>
                <span
                  v-if="
                    infoList.data.mergedOrders &&
                    infoList.data.mergedOrders.length > 3
                  "
                >
                  <span
                    v-for="(
                      item, itemIndex
                    ) in infoList.data.mergedOrders.slice(0, 2)"
                    :key="itemIndex"
                  >
                    <a class="slip-edit" @click="getNew(item.id)">{{
                      item.orderNo
                    }}</a>
                    <span v-if="itemIndex < 1">,</span>
                  </span>
                  <el-dropdown @command="handleCommand">
                    <span class="el-dropdown-link slip-edit">
                      更多<i class="el-icon-arrow-down el-icon--right"></i>
                    </span>
                    <template #dropdown>
                      <el-dropdown-menu>
                        <el-dropdown-item
                          v-for="(
                            item, index
                          ) in infoList.data.mergedOrders.slice(
                            2,
                            infoList.data.mergedOrders.length
                          )"
                          :key="index"
                          :command="item.id"
                          >{{ item.orderNo }}
                        </el-dropdown-item>
                      </el-dropdown-menu>
                    </template>
                  </el-dropdown>
                </span>
              </template>
              <template v-slot:basic-mergedOrder>
                <a
                  v-if="infoList.data.mergeOrder"
                  class="slip-edit"
                  @click="getNew(infoList.data.mergeOrder.id)"
                  >{{ infoList.data.mergeOrder.orderNo }}</a
                >
              </template>
              <template v-slot:basic-quoteContractNos>
                <span v-if="infoList.data.purchAccording === 2">
                  {{ infoList.data.quoteContractNos }}
                </span>
              </template>
            </basic-information>
          </div>
        </div>

        <div class="model-panel">
          <div class="model-panel-title">
            <Tooltip :text="$t('detailInfo')"></Tooltip>
            <div class="model-tips">
              (证照：<span>近效期</span>
              <span class="model-tips-nearly"></span>
            </div>
            <div class="model-tips">
              <span>过期</span>
              <span class="model-tips-expire"></span>)
            </div>
          </div>
          <div class="model-panel-body">
            <div class="flex-end" style="margin-bottom: 7px">
              <el-button @click="preferenceInfo.visible = true"
                >偏好设置</el-button
              >
            </div>
            <div class="flex_full_item">
              <!-- 表格 -->
              <page-table
                :refresh="tableInfo.refresh"
                :init-curpage="tableInfo.initCurpage"
                v-model:data="tableInfo.data"
                :api="tableInfo.api"
                :pager="false"
                :summary="true"
                :summary-field-list="tableInfo.summaryFieldList"
                :check-box="false"
                :tab-index="true"
                :query="filterInfo.query"
                :field-list="tableInfo.fieldList"
                :handle="tableInfo.handle"
                :row-class-name="tableRowClassName"
                :isDynamic="true"
                @sortChange="sortChange"
              >
              </page-table>
            </div>
          </div>
        </div>
      </NewFullScreen>
    </div>
    <purch-application-detail
      v-if="purchAppDetailinfo.visible"
      v-model:visible="purchAppDetailinfo.visible"
      :table-row="purchAppDetailinfo.data"
    />
    <purch-application-summary-detail
      v-if="summaryDetailInfo.visible"
      v-model:visible="summaryDetailInfo.visible"
      :table-row="summaryDetailInfo.data"
      @returnBack="getList"
    />
    <purch-order-modify
      v-if="modifyInfo.visible"
      v-model:visible="modifyInfo.visible"
      :title="modifyInfo.title"
      :tableKey="modifyInfo.tableKey"
      :orderId="modifyInfo.orderId"
      :purchAccording="infoList.data.purchAccording"
      :is-copy="modifyInfo.isCopy"
      @returnModify="returnModify"
    />
    <TemplateModify
      v-if="templateModifyInfo.visible"
      v-model:visible="templateModifyInfo.visible"
      :purchOrderId="templateModifyInfo.purchOrderId"
      :title="templateModifyInfo.title"
    />
    <SetPreferenceNoQuery
      v-if="preferenceInfo.visible"
      v-model:visible="preferenceInfo.visible"
      :searchList="filterInfo.searchList"
      :fieldList="tableInfo.fieldList"
      :customizeUserVO="filterInfo.query.customizeUserVO"
      :groupLevelShow="false"
      @callback="setPreferenceCallback"
    />
  </div>
</template>

<!-- <script>
import detailPageViewMixin from '@/mixins/detailPageViewMixin'
export default {
  mixins: [detailPageViewMixin],
}
</script> -->

<script setup name="purchOrderDetailDemo">
import {
  purchOrdersDetailCustomizeListAll,
  purchOrderById,
  methodPurchOrder,
  exportPurch,
  getPurchOrderPrint,
} from '@/api/purch'
import { orderAffairAll } from '@/api/affair'
import { getCoreSystemConfigGetConfigValue } from '@/api/core'
import { getCustomizeSetting, updateUserCustomize } from '@/api/customize'
import { fatchTemplateByCode } from '@/api/base'
import PurchApplicationDetail from '../application/detail'
import PurchOrderModify from './modify'
import PurchApplicationSummaryDetail from '@/views/purch/applicationSummary/detail'
import _ from 'lodash'
const TemplateModify = defineAsyncComponent(() => import('../template/modify'))
const SetPreferenceNoQuery = defineAsyncComponent(() =>
  import('@/components/SetPreference/setPreferenceNoQuery')
)
const emits = defineEmits()
const { proxy } = getCurrentInstance()
const props = defineProps(['visible', 'orderId'])

const tableKey = ref(
  'purchOrderDetail-com.slip.spd.entity.vo.purch.PurchOrderDetailVO'
)
const infoList = ref({
  data: {},
  fieldList: [
    { label: '采购单号', value: 'orderNo', type: 'text' },
    { label: '申购单号', value: 'applicationNo', type: 'slot' },
    { label: '供应商', value: 'supplierName', type: 'text' },
    { label: '部门', value: 'deptName', type: 'text' },
    { label: '收货联系人', value: 'receiveContacts', type: 'text' },
    { label: '收货电话', value: 'receivePhone', type: 'text' },
    { label: '收货地址', value: 'receiveAddressValue', type: 'popover' },
    { label: '状态', value: 'statusValue', type: 'text' },
    { label: '创建人', value: 'createUserName', type: 'text' },
    { label: '创建时间', value: 'createTime', type: 'text' },
    { label: '采购人', value: 'purchUserName', type: 'text' },
    { label: '采购时间', value: 'purchTime', type: 'text' },
    { label: '最后收货时间', value: 'lastReceiveTime', type: 'text' },
    { label: '最后入库时间', value: 'lastStoreTime', type: 'text' },
    { label: '新订单号', value: 'mergedOrder', type: 'slot' },
    { label: '原订单号', value: 'mergedOrders', type: 'slot' },
    { label: '采购依据', value: 'purchAccordingValue', type: 'text' },
    {
      label: '是否寄售业务',
      value: 'isConsignBusinessValue',
      type: 'text',
      show: proxy.$store.state.permission.systemConfig.is_consign_business == 1,
    },
    { label: '备注', value: 'remark', type: 'text' },
  ],
})
// 过滤相关配置
const filterInfo = ref({
  sortArr: [],
  copyQueryMap: {},
  query: {
    queryMap: {
      orderId: {
        queryType: 'EQUALS',
        queryCategory: 'AND',
        value: null,
      },
    },
    queryParams: {},
  },
  searchList: [],
  searchBtn: [],
  btnList: [],
})
//另存为模板参数
const templateModifyInfo = ref({
  visible: false,
  purchOrderId: '',
  title: '另存为模板',
})
const purchAppDetailinfo = ref({
  visible: false,
  title: '申购单明细',
  data: {},
})
const summaryDetailInfo = ref({
  visible: false,
  title: '申购单汇总明细',
  data: {},
})
// 表格相关
const tableInfo = ref({
  api: undefined,
  summaryFieldList: [
    { value: 'qty', formatter: proxy.$fn.qtyFormatter },
    { value: 'sumAmount', formatter: proxy.$fn.TripartiteMethod },
  ],
  fieldList: [],
  refresh: 1,
  initCurpage: 1,
  data: [],
  selections: [],
})
const affairTableInfo = ref({
  api: orderAffairAll,
  query: {
    orderType: 'purch_order',
    orderId: props.orderId,
    sort: 'operate_time desc',
  },
})
const modifyInfo = ref({
  visible: false,
  title: '',
  orderId: '',
  tableKey: '',
  isCopy: false,
})
const preferenceInfo = ref({
  visible: false,
})
const systemConfig = ref('')
const showDialog = computed({
  get() {
    return props.visible
  },
  set(newValue) {
    emits('update:visible', newValue) // 更新父组件shows
  },
})
const canPrint = computed(() => {
  return (
    proxy.$permission('purchOrder:print') && infoList.value.data.status !== 1
  )
})
const canExcel = computed(() => {
  return (
    proxy.$permission('purchOrder:excel') && infoList.value.data.status !== 1
  )
})
// 驳回
const canReject = computed(() => {
  return (
    proxy.$permission('purchOrder:reject') && infoList.value.data.status === 2
  )
})
//拆单
const canSplit = computed(() => {
  return (
    proxy.$permission('purchOrder:split') &&
    (infoList.value.data.status === 1 ||
      infoList.value.data.status === 2 ||
      infoList.value.data.status === 3) &&
    infoList.value.data.mergedOrders.length > 0 &&
    infoList.value.data.status === infoList.value.data.beforeMergeStatus
  )
})
const canDoPurch = computed(() => {
  return (
    proxy.$permission('purchOrder:doPurch') && infoList.value.data.status === 3
  )
})
const canSubmit = computed(() => {
  return (
    proxy.$permission('purchOrder:submit') && infoList.value.data.status === 1
  )
})
const canRatify = computed(() => {
  return (
    proxy.$permission('purchOrder:ratify') && infoList.value.data.status === 2
  )
})
const canRevoke = computed(() => {
  return (
    proxy.$permission('purchOrder:revoke') &&
    (infoList.value.data.status === 2 ||
      (infoList.value.data.status === 3 &&
        proxy.$store.state.permission.systemConfig.allow_purch_order_approval !=
          1))
  )
})
const canBreak = computed(() => {
  return (
    proxy.$permission('purchOrder:stop') &&
    ((infoList.value.data.status === 3 &&
      proxy.$store.state.permission.systemConfig.allow_purch_order_approval ===
        1) ||
      infoList.value.data.status === 13 ||
      infoList.value.data.status === 14)
  )
})

setData()
function setData() {
  let obj = {
    price: {
      label: '单价',
      value: 'price',
      type: 'column',
      formatter: proxy.$fn.TripartiteMethod,
      permission: !proxy.$permission('purchOrder:price'),
      hidden: true,
    },
    orderNo: {
      label: '单号',
      value: 'orderNo',
      componentType: 'input',
      show: false,
      type: 'column',
      hidden: true,
    },
    sumAmount: {
      label: '总金额',
      value: 'sumAmount',
      type: 'column',
      formatter: proxy.$fn.TripartiteMethod,
      permission: !proxy.$permission('purchOrder:price'),
      hidden: true,
    },
    defaultSupplierPrice: {
      label: '默认供应商价格',
      value: 'defaultSupplierPrice',
      type: 'column',
      permission: !proxy.$permission('purchOrder:price'),
      formatter: proxy.$fn.TripartiteMethod,
      hidden: true,
    },
  }
  tableInfo.value.fieldList = Object.values({
    ...proxy.$fn.deepClone(proxy.$fieldfList.FieldList),
    ...obj,
  })
  getCustomize()
}
function sortChange(column) {
  let _filterInfo = filterInfo.value
  if (_filterInfo.query.customizeUserVO.head.sortType === 0) {
    let arr = proxy.$fn.sortChange(column, _filterInfo.sortArr)
    _filterInfo.sortArr = arr
    _filterInfo.query.sortString = arr.length ? arr.toString() : ''
    getList()
  }
}
function setPreferenceCallback(obj) {
  updateUserCustomize(obj.customizeUserVO).then((res) => {
    if (res && res.success) {
      getCustomize()
    }
  })
}
//拷贝
function copyPurchOrder() {
  modifyInfo.value.visible = true
  modifyInfo.value.isCopy = true
  modifyInfo.value.title = '拷贝采购单'
  // 显示信息
  modifyInfo.value.orderId = props.orderId
  modifyInfo.value.purchAccording = infoList.value.data.purchAccording
  if (
    infoList.value.data.purchType === 0 ||
    infoList.value.data.purchType === 1
  ) {
    modifyInfo.value.tableKey =
      'purchOrderDetailModifyByApplication-com.slip.spd.entity.vo.purch.PurchOrderDetailVO'
  } else {
    modifyInfo.value.tableKey =
      'purchOrderDetailModify-com.slip.spd.entity.vo.purch.PurchOrderDetailVO'
  }
}
//另存为模板
function saveCopeTemplate() {
  templateModifyInfo.value.visible = true
  templateModifyInfo.value.purchOrderId = props.orderId
}
function returnModify() {
  if (props.orderId) {
    getCustomize()
  }
}

//导出excel
function exportExcel() {
  exportPurch(filterInfo.value.query).then((resp) => {
    if (resp) {
      proxy.$fn.parseExcel(resp)
    }
  })
}
//打印
function print() {
  fatchTemplateByCode({
    resourceCode: 'purchOrder:print',
    isDefault: 1,
  }).then((res) => {
    if (res && res.success) {
      let temp = proxy.$fn.getPrintTemp(res.data[0])
      getPirntData(temp)
    }
  })
}
function getPirntData(temp) {
  let params = {
    tableKey:
      'purchOrderDetail-com.slip.spd.entity.vo.purch.PurchOrderDetailVO',
    orderIds: [props.orderId],
  }
  getPurchOrderPrint(params).then((res) => {
    if (res.success && res) {
      let data = proxy.$fn.deepClone(res.data)
      let newData = data.map((item) => {
        return {
          ...item,
          ...item.orderInfo,
        }
      })
      proxy.$lodop.preview(
        temp,
        newData,
        !proxy.$permission('purchOrder:price')
      )
    }
  })
}
function showPurchAppDetail(data) {
  var obj = {}
  obj.id = data.applicationId
  let purchType = data.purchType
  if (purchType === 0) {
    purchAppDetailinfo.value.visible = true
    purchAppDetailinfo.value.data = { ...obj }
  } else if (purchType === 1) {
    summaryDetailInfo.value.visible = true
    summaryDetailInfo.value.data = { ...obj }
  }
}
function getOrderInfo(orderId) {
  purchOrderById(orderId).then((resp) => {
    if (resp && resp.success) {
      infoList.value['data'] = resp.data
    }
    const item = _.find(infoList.value.fieldList, ['label', '引用合同编号'])
    if (infoList.value.data.purchAccording === 2 && !item) {
      infoList.value.fieldList.push({
        label: '引用合同编号',
        value: 'quoteContractNos',
        type: 'slot',
        className: 'not-br',
      })
    }
  })
}
function update() {
  modifyInfo.value.visible = true
  modifyInfo.value.isCopy = false
  modifyInfo.value.title = '修改采购单'
  // 显示信息
  modifyInfo.value.orderId = props.orderId
  if (
    infoList.value.data.purchType === 0 ||
    infoList.value.data.purchType === 1
  ) {
    modifyInfo.value.tableKey =
      'purchOrderDetailModifyByApplication-com.slip.spd.entity.vo.purch.PurchOrderDetailVO'
  } else {
    modifyInfo.value.tableKey =
      'purchOrderDetailModify-com.slip.spd.entity.vo.purch.PurchOrderDetailVO'
  }
}
function handelMethodRequest(method) {
  const ids = getIds(infoList.value.data)
  if (method === 'reject') {
    proxy
      .$prompt('请输入驳回理由', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        inputValidator: proxy.$fn.maxString200,
        inputErrorMessage: '驳回理由不能超过200字符',
      })
      .then(({ value }) => {
        const data = {
          id: infoList.value.data.id,
          rejectReason: value,
        }
        methodPurchOrder(data, method).then((resp) => {
          if (resp && resp.success) {
            getCustomize()
          }
        })
      })
  } else {
    methodPurchOrder(ids, method).then((resp) => {
      if (resp.success) {
        getCustomize()
      }
    })
  }
}
function getIds(row = undefined) {
  let ids = []
  if (row) {
    ids.push(row.id)
  } else {
    ids = tableInfo.value.selections.map((row) => row.id)
  }
  return ids
}
function receiving(row) {
  proxy.$router.push({
    name: 'receivingOrder',
    params: {
      orderId: row.id,
    },
  })
}
// 触发事件
function handleEvent(event, data) {
  switch (event) {
    case 'tableCheck':
      tableInfo.value.selections = [...data]
      break
  }
}
function getNew(id) {
  getOrderInfo(id)
  filterInfo.value.query.queryMap.orderId.value = id
  affairTableInfo.value.query.orderId = id
  getList()
}
function handleCommand(id) {
  getNew(id)
}
function getValueList() {
  getCoreSystemConfigGetConfigValue({
    systemConfigCode: 'license_nearly_effective',
  }).then((resp) => {
    if (resp && resp.success) {
      systemConfig.value = resp.data
    }
  })
}
function tableRowClassName({ row = undefined }) {
  if (row.licenseEndDate) {
    let dataDiff = proxy.$fn.dateDiffLicen(row.licenseEndDate)
    if (dataDiff <= 0) {
      return 'expire-row'
    } else if (Number(systemConfig.value) >= dataDiff) {
      return 'nearly-row'
    }
  }
  return ''
}
function getCustomize() {
  let _tableInfo = tableInfo.value
  let param = {
    tableKey: tableKey.value,
  }
  getCustomizeSetting(param).then((res) => {
    if (res && res.success) {
      let data = res.data
      _tableInfo.fieldList = proxy.$fn.setFieldList(
        _tableInfo.fieldList,
        data.detail
      )
      filterInfo.value.query.customizeUserVO = data
      filterInfo.value.query.queryMap.orderId.value = props.orderId
      _tableInfo.api = purchOrdersDetailCustomizeListAll
      getValueList()
      getOrderInfo(props.orderId)
      getList()
    }
  })
}
function returnBack() {
  emits('returnBack', false)
}
function getList() {
  purchOrdersDetailCustomizeListAll(filterInfo.value.query).then((resp) => {
    if (resp && resp.success) {
      tableInfo.value.data = resp.data
    }
  })
}
</script>
<style scoped lang="scss">
:deep(.page-table) > .el-table {
  overflow-y: hidden;
}
.model-panel-title {
  display: flex;
  align-items: center;
  .model-tips {
    display: flex;
    align-items: center;
    margin-left: 10px;
    color: #909399;
    .model-tips-nearly,
    .model-tips-expire {
      display: block;
      margin-left: 5px;
      width: 17px;
      height: 17px;
    }
    .model-tips-nearly {
      background: #fceacb;
    }
    .model-tips-expire {
      background: #f5e4e4;
    }
  }
}
:deep(.el-table) {
  .nearly-row {
    background: #fceacb;
  }
  .expire-row {
    background: #f5e4e4;
  }
}
</style>
